package com.wft.design.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wft.design.common.mybatis.service.impl.BaseServiceImpl;
import com.wft.design.upms.constant.BasicData;
import com.wft.design.upms.entity.SysRole;
import com.wft.design.upms.mapper.SysRoleMapper;
import com.wft.design.upms.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author WFT
 * @date 2020/2/6
 * description:
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Override
    public List<SysRole> selectList(SysRole role) {
        LambdaQueryWrapper<SysRole> wrapper = Wrappers.lambdaQuery();
        //  过滤系统角色
        wrapper.notIn(SysRole::getId, BasicData.ROLE_ID);
        if (null != role){
            //  根据名称模糊查询
            if (StringUtils.hasText(role.getRoleName())){
                wrapper.likeRight(SysRole::getRoleName,role.getRoleName());
            }
        }
        return this.list(wrapper);
    }

    /**
     * 根据名称获取角色信息
     * @param name java.lang.String
     * @return com.wft.design.upms.entity.SysRole
     */
    private SysRole selectByName(String name){
        return this.getOne(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getRoleName,name));
    }

    @Override
    public void createRole(SysRole role) {
        Assert.isNull(this.selectByName(role.getRoleName()),"角色名称已存在");
        LocalDateTime now = LocalDateTime.now();
        role.setCreateTime(now);
        role.setLastModifyTime(now);
        this.save(role);
    }

    @Override
    public SysRole selectById(Long roleId) {
        return this.getById(roleId);
    }

    @Override
    public void updateRole(SysRole role) {
        SysRole dbRole = this.selectById(role.getId());
        Assert.notNull(dbRole,"角色Id不存在");
        //  判断是否修改了角色名称
        if (!role.getRoleName().equals(dbRole.getRoleName())){
            Assert.isNull(this.selectByName(role.getRoleName()),"角色名称已存在");
        }
        role.setCreateTime(dbRole.getCreateTime());
        role.setLastModifyTime(LocalDateTime.now());
        this.updateById(role);
    }

    @Override
    public void deleteRole(Long roleId) {
        this.removeById(roleId);
    }

}
